﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Chinesys.Domain.InputValidations;
using Chinesys.UI.Helpers;

namespace Chinesys.UI.Account
{
    public partial class Login : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.PageTitle = "Inicio de Sesión";

            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);

            if (!String.IsNullOrEmpty(Request.Params["action"]))
            {
                if (Request.Params["action"] == "logout")
                {
                    FormsAuthentication.SignOut();
                    Master.UserRole = string.Empty;
                }
            }

            if (!IsPostBack)
            {
                if (!String.IsNullOrEmpty(Request.Params["error"]))
                {
                    string error = Request.Params["error"];

                    if (error == "notLogged")
                        hdnBizRulesException.Value = "Debes iniciar sesión para poder ingresar a esa sección.";

                    if (error == "invalidRole")
                        hdnBizRulesException.Value = "No tienes permisos suficientes para ingresar a esa sección.";
                }
            }
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            List<InputValidationError> errors = new List<InputValidationError>();

            string username = TypeHelper.ConvertToType<String>(txtUserName.Text, "Nombre de Usuario", errors);
            string password = TypeHelper.ConvertToType<String>(txtPassword.Text, "Password", errors);

            if (errors.Any())
            {
                validationSummary.Errors = errors;
                return;
            }

            string role;
            if (SecurityHelper.LogOnUser(username, password, out role))
            {
                Master.UserRole = role;
                FormsAuthentication.RedirectFromLoginPage(username, RememberMe.Checked);
            }
            else
                failureText.Text = "El usuario o la contraseña no son validos.";
        }
    }
}
